package com.jack.leetcode.每日一题;

/***
 * @author zhangjie
 * @date 2020/4/4 13:46
 */
public class 接雨水 {

    public static void main(String[] args) {
        int[] a = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
        int[] b = {2,0,2};
        System.out.println(trap(a));
        System.out.println(trap(b));
    }

    public static int trap(int[] height) {
        int result = 0;
        int n = height.length;
        int[] max_left = new int[n];
        int[] max_right = new int[n];
        for (int i = 1; i < n; i++) {
            max_left[i] = Math.max(max_left[i - 1], height[i-1]);
        }
        for (int i = n - 2; i >= 0; i--) {
            max_right[i] = Math.max(max_right[i + 1], height[i + 1]);
        }
        for (int i = 0; i < n; i++) {
            int min = Math.min(max_left[i], max_right[i]);
            if (height[i] < min) {
                result += (min - height[i]);
            }
        }
        return result;
    }

    public static int trap1(int[] height) {
        if (height.length == 0) {
            return 0;
        }
        int max = height[0];
        for (int i = 1; i < height.length; i++) {
            if (max < height[i]) {
                max = height[i];
            }
        }
        int result = 0;
        for (int i = 1; i <= max; i++) {
            int start = 0, end = 0;
            for (int j = 0; j < height.length; j++) {
                if (height[j] >= i) {
                    start = j;
                    break;
                }
            }
            for (int j = height.length - 1; j >= 0; j--) {
                if (height[j] >= i) {
                    end = j;
                    break;
                }
            }
            for (int j = start; j <= end; j++) {
                if (height[j] < i) {
                    result++;
                }
            }
        }
        return result;
    }
}
